package demo3;

import java.util.Arrays;

//循环队列
public class CircularQueue {
    //用来记录数组的有效数字的个数
    public int[] elem;
    public int last;
    public int first;

    public CircularQueue(int[] arr) {
        this.elem = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            this.elem[i] = arr[i];
        }
        this.first = 0;
        this.last = arr.length % this.elem.length;
    }

    //入队列
    public boolean offer(int val) {
        if (isFull()) {
            return false;
        }

        this.elem[last] = val;
        last = (last + 1) % this.elem.length;
        return true;
    }

    //出队列
    public int poll() {
        //如果数组为空 就返回一个 -1
        if (isEmpty()) {
            return -1;
        }
        int val = this.elem[first];
        this.first = (this.first + 1) % this.elem.length;
        return val;
    }

    //获取队头元素
    public int peek() {
        //如果数组为空 就返回一个 -1
        if (isEmpty()) {
            return -1;
        }
        return this.elem[first];
    }

    public boolean isEmpty() {
        return this.first == this.last;
    }
    //获取队列中有效元素个数
    public int size() {
        int f = this.first;
        int count = 0;
        while (f != this.last) {
            count++;
            f = (f + 1) % this.elem.length;
        }
        return count;
    }
    //判断数组是否为满
    public boolean isFull() {
        return (this.last + 1) % this.elem.length == this.first;
    }
}
